﻿using Cxuu.Common;
using Cxuu.Models;
using Cxuu.Service;
using Cxuu.Web.Authorize;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Cxuu.Web.Admin
{
    [Area("Admin")]
    [Authorize]
    public class ExamineController : Base
    {
        private readonly LogService _logService;
        private readonly LoginUtil _LoginUtil;
        private readonly AdminUserService _adminUserService;
        private readonly ArticleExamineService _articleExamineService;

        public ExamineController(LoginUtil LoginUtil, LogService logService, ArticleExamineService articleExamineService, AdminUserService adminUserService)
        {
            _LoginUtil = LoginUtil;
            _logService = logService;
            _articleExamineService = articleExamineService;
            _adminUserService = adminUserService;
        }

        [HttpGet]
        [ActionPermissionFilter(Permission = PermissionKeys.ArticleExamine_Index)]
        public async Task<IActionResult> IndexAsync([FromQuery] ArticleExamineQuery query, int json = 0)
        {
            if (json == 1)
            {
                ArticleExamineQuery articleQuery = new()
                {
                    UserId = await _LoginUtil.LoginUserId(),
                    PostId = 0,
                    Page = query.Page,
                    Limit = query.Limit,
                    Title = query.Title,
                    NickName = query.NickName,
                    Remarks = query.Remarks,
                    Status = query.Status,
                    Pass = query.Pass,
                };

                var pagedList = await _articleExamineService.GetListAsync(articleQuery);
                return Json(new { code = 0, count = pagedList.TotalItems, data = pagedList.Items });
            }
            return View();
        }
        [HttpGet]
        [ActionPermissionFilter(Permission = PermissionKeys.ArticleExamine_Index)]
        public async Task<IActionResult> PostIndexAsync([FromQuery] ArticleExamineQuery query, int json = 0)
        {
            if (json == 1)
            {
                ArticleExamineQuery articleQuery = new()
                {
                    PostId = await _LoginUtil.LoginUserId(),
                    Page = query.Page,
                    Limit = query.Limit,
                    Title = query.Title,
                    Remarks = query.Remarks,
                    Status = query.Status,
                    Pass = query.Pass,
                };

                var pagedList = await _articleExamineService.GetListAsync(articleQuery);
                return Json(new { code = 0, count = pagedList.TotalItems, data = pagedList.Items });
            }
            return View();
        }


        #region 提供JSON调用
        [HttpGet]
        [ActionPermissionFilter(Permission = PermissionKeys.ArticleExamine_Post)]
        public async Task<IActionResult> GetExamineByAidAsync([FromQuery] int id)//id  = aid  报审位置使用
        {
            int userId = await _LoginUtil.LoginUserId();
            ViewExamine examine = await _articleExamineService.GetEditByAidAsync(id);
            ViewArtExamine article = await _articleExamineService.GetArtNoContentAsync(id);
            List<ViewArticleExamine> articleList = await _articleExamineService.GetExamineingAsync(id);

            //判断自己在当前文件审核流转中是否已经提交过审核
            int isPost = (int)ExaminePassTypeEnum.Type.不通过;
            if (articleList.Exists(t => t.PostId == userId))
            {
                isPost = (int)ExaminePassTypeEnum.Type.通过;
            }

            //判断当前文件是不是自己的，不然就不能进行报审操作
            int owns = 1;
            if (userId != article.ArtUserId)
            {
                owns = 0;//不是自己的
            }

            return Json(new { status = 1, isPost, owns, data = examine, art = article, list = articleList });
        }
        [HttpGet]
        [ActionPermissionFilter(Permission = PermissionKeys.ArticleExamine_Post)]
        public async Task<IActionResult> GetExamineByIdAsync([FromQuery]int id)
        {
            int userId = await _LoginUtil.LoginUserId();
            ViewExamine examine = await _articleExamineService.GetEditByIdAsync(id);
            ViewArtExamine article = await _articleExamineService.GetArtAsync(examine.Aid);
            List<ViewArticleExamine> articleList = await _articleExamineService.GetExamineingAsync(examine.Aid);
            //判断自己在当前文件审核流转中是否已经提交过审核
            int isPost = (int)ExaminePassTypeEnum.Type.不通过;
            if (articleList.Exists(t => t.PostId == userId))
            {
                isPost = (int)ExaminePassTypeEnum.Type.通过;
            }

            //判断当前文件审核不是自己提交的
            int myexa = 0;
            if (userId == examine.UserId)
            {
                myexa = 1;//是自己的
            }

            return Json(new { status = 1, isPost, myexa, data = examine, art = article, list = articleList });
        }
        [HttpGet]
        [ActionPermissionFilter(Permission = PermissionKeys.ArticleExamine_Post)]
        public async Task<IActionResult> GetUserAsync(string name)
        {
            List<UserIdAndName> userIdAndName = await _adminUserService.GetNameAsync(0,name);
            return Json(new { status = 1, data = userIdAndName });
        }
        #endregion

        #region 提交审核
        [HttpGet]
        [ActionPermissionFilter(Permission = PermissionKeys.ArticleExamine_Post)]
        public IActionResult PostExamineByIdAsync()
        {
            return View();
        }

        [HttpGet]
        [ActionPermissionFilter(Permission = PermissionKeys.ArticleExamine_Post)]
        public IActionResult PostExamineByAidAsync()
        {
            return View();
        }

        [HttpPost]
        [ActionPermissionFilter(Permission = PermissionKeys.ArticleExamine_Post)]
        [Log(Name = "提交报审")]
        public async Task<IActionResult> PostExamineAsync(ViewArticleExamine query)
        {
            UserAction adminUser = _LoginUtil.UserAction();
            query.PostId = adminUser.UserId;
            int res = await _articleExamineService.InsertOrUpdateAsync(query, adminUser);
            return res switch
            {
                100 => Json(new { status = 1, msg = "提交报审报送文件 ID：" + query.Aid }),
                101 => Json(new { status = 1, msg = "修改审核人-报送文件 ID：" + query.Aid }),
                400 => Json(new { status = 0, msg = "审核已办结，流程已经终止！" }),
                401 => Json(new { status = 0, msg = "操作太快，请勿重复提交，15秒后重试！" }),
                402 => Json(new { status = 0, msg = "未选择审核人！" }),
                403 => Json(new { status = 0, msg = "报审内容没有变化！" }),
                404 => Json(new { status = 0, msg = "不能选择自己为审核人！" }),
                405 => Json(new { status = 0, msg = "你选择的审核人已经在本流程中，请重新选择！" }),
                _ => Json(new { status = 0, msg = "报审失败！请联系管理员！" }),
            };
        }
        #endregion

        #region 审核文件
        [HttpGet]
        [ActionPermissionFilter(Permission = PermissionKeys.ArticleExamine_Update)]
        public IActionResult EditExamineAsync()
        {
            return View();
        }
        [HttpPost]
        [ActionPermissionFilter(Permission = PermissionKeys.ArticleExamine_Update)]
        [Log(Name = "审核报送文件")]
        public async Task<IActionResult> EditPostAsync(ArticleExamine query)
        {
            ArticleExamine articleExamine = new()
            {
                Id = query.Id,
                Remarks = query.Remarks,
                Pass = query.Pass,
            };
            if (0 < await _articleExamineService.EditPostAsync(articleExamine))
            {
                return Json(new { status = 1, msg = "审核报送文件 ID：" + query.Id });
            }
            else
                return Json(new { status = 0, msg = "审核操作失败" });
        }
        #endregion
    }
}
